import { addDialog, closeDialog } from "@/components/ReDialog";
import { h, Ref} from "vue";
import { isFunction } from "@pureadmin/utils";
import Sortable from "sortablejs";
import { VXETable } from "vxe-table";
import {VxeGridInstance} from "vxe-table/types/grid";

export class CommonUtils {
  /**
   * 打开基本弹窗
   * @param message 弹框提示的内容
   */
  static openBaseModal(message: string) {
    addDialog({
      title: "Error",
      closeOnClickModal: false, //点击空白页时是否关闭弹窗
      contentRenderer: () => h("p", message),
      footerButtons: [
        {
          label: "confirm",
          type: "primary",
          btnClick: ({ dialog: { options, index } }) => {
            const done = () =>
              closeDialog(options, index, { command: "cancel" });
            if (options?.beforeCancel && isFunction(options?.beforeCancel)) {
              options.beforeCancel(done, { options, index });
            } else {
              done();
            }
          }
        }
      ]
    });
  }

  /**
   * Table 的列拖动方法
   * @param gridInstance Table实例
   * @returns Sortable Sortable的实例
   */
  static columnDrop(gridInstance: Ref<VxeGridInstance>): Sortable {
    const $grid = gridInstance.value;
    return Sortable.create(
      $grid.$el.querySelector(
        ".body--wrapper>.vxe-table--header .vxe-header--row"
      ),
      {
        //标记选择器，不包含fixed列
        handle: ".vxe-header--column:not(.col--fixed)",
        onStart: sortableEvent => {
          console.log(sortableEvent);
          // if()
        },
        onEnd: sortableEvent => {
          const targetThElem = sortableEvent.item;
          const newIndex = sortableEvent.newIndex as number;
          const oldIndex = sortableEvent.oldIndex as number;
          const { fullColumn, tableColumn } = $grid.getTableColumn();
          const wrapperElem = targetThElem.parentNode as HTMLElement;
          const newColumn = fullColumn[newIndex];
          //如果目标位置列是fixed则不可以移动到目标位置上
          if (newColumn.fixed) {
            // 错误的移动
            const oldThElem = wrapperElem.children[oldIndex] as HTMLElement;
            if (newIndex > oldIndex) {
              wrapperElem.insertBefore(targetThElem, oldThElem);
            } else {
              wrapperElem.insertBefore(
                targetThElem,
                oldThElem ? oldThElem.nextElementSibling : oldThElem
              );
            }
            VXETable.modal.message({
              content: "固定列不允许拖动！",
              status: "error"
            });
            return;
          }
          // 获取列索引 columnIndex > fullColumn
          const oldColumnIndex = $grid.getColumnIndex(tableColumn[oldIndex]);
          const newColumnIndex = $grid.getColumnIndex(tableColumn[newIndex]);
          // 移动到目标列
          const currRow = fullColumn.splice(oldColumnIndex, 1)[0];
          fullColumn.splice(newColumnIndex, 0, currRow);
          $grid.loadColumn(fullColumn);
        }
      }
    );
  }
}
